<template>
  <view class="bg-[#f5f7fa] w-[750rpx] min-h-screen flex flex-col items-center justify-center py-[40rpx] px-[30rpx]">
    <!-- 授权回调处理页面 -->
    <view class="w-full max-w-[600rpx] bg-white rounded-[25rpx] shadow-[0_4rpx_20rpx_rgba(0,0,0,0.1)] overflow-hidden">
      <!-- 头部 -->
      <view class="bg-gradient-to-r from-[#07C160] to-[#00D4AA] p-[40rpx] text-white text-center">
        <IconFont name="icon-wechat" class="text-[60rpx] mb-[20rpx]" />
        <text class="text-[36rpx] font-bold">微信授权</text>
      </view>
      
      <!-- 内容区域 -->
      <view class="p-[40rpx] text-center">
        <view v-if="isProcessing" class="mb-[30rpx]">
          <view class="loading-spinner w-[60rpx] h-[60rpx] border-[4rpx] border-[#e5e7eb] border-t-[#07C160] rounded-full animate-spin mx-auto mb-[20rpx]"></view>
          <text class="text-[28rpx] text-[#666]">正在处理授权信息...</text>
          <text class="block text-[14rpx] text-[#999] mt-[10rpx]">请稍候，不要关闭页面</text>
        </view>
        
        <view v-else-if="isSuccess" class="mb-[30rpx]">
          <view class="success-icon w-[60rpx] h-[60rpx] bg-[#07C160] rounded-full flex items-center justify-center mx-auto mb-[20rpx]">
            <IconFont name="check" class="text-[30rpx] text-white" />
          </view>
          <text class="text-[28rpx] text-[#333] font-medium">授权成功！</text>
          <text class="block text-[14rpx] text-[#666] mt-[10rpx]">正在跳转到首页...</text>
        </view>
        
        <view v-else-if="isError" class="mb-[30rpx]">
          <view class="error-icon w-[60rpx] h-[60rpx] bg-[#FF4D4F] rounded-full flex items-center justify-center mx-auto mb-[20rpx]">
            <IconFont name="close" class="text-[30rpx] text-white" />
          </view>
          <text class="text-[28rpx] text-[#333] font-medium">授权失败</text>
          <text class="block text-[14rpx] text-[#666] mt-[10rpx]">{{ errorMessage }}</text>
        </view>
        
        <!-- 重试按钮 -->
        <view v-if="isError" class="mt-[40rpx]">
          <nut-button
            type="primary"
            size="large"
            class="w-full bg-[#07C160] text-white border-none rounded-[12rpx] py-[16rpx] text-[18rpx] font-medium shadow-[0_4rpx_12rpx_rgba(7,193,96,0.3)] transition-all duration-300"
            @click="handleRetry"
          >
            重新授权
          </nut-button>
          
          <nut-button
            type="default"
            size="large"
            class="w-full mt-[20rpx] bg-white text-[#666] border border-[#ddd] rounded-[12rpx] py-[16rpx] text-[18rpx] font-medium"
            @click="goBackToLogin"
          >
            返回登录页
          </nut-button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import Taro from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
import { wechatAuth } from '@/core/config';
import { post } from '@/utils/request';

/**
 * 微信授权回调页面
 * @description 处理微信授权后的回调逻辑，获取授权code并换取token
 */

// 处理状态
const isProcessing = ref<boolean>(true);
const isSuccess = ref<boolean>(false);
const isError = ref<boolean>(false);
const errorMessage = ref<string>('');
const isDebugMode = ref<boolean>(false);
const DEBUG_LOG_STORAGE_KEY = "authDebugLogs";
const DEBUG_ENABLE_STORAGE_KEY = "authDebugEnabled";

interface DebugLogEntry {
  timestamp: number;
  message: string;
}

/**
 * 追加调试日志到缓存
 * @param payload 调试日志内容
 */
const appendDebugLog = (payload: DebugLogEntry) => {
  try {
    const cache: DebugLogEntry[] = Taro.getStorageSync(DEBUG_LOG_STORAGE_KEY) || [];
    const nextCache = [...cache, payload];
    if (nextCache.length > 30) {
      nextCache.splice(0, nextCache.length - 30);
    }
    Taro.setStorageSync(DEBUG_LOG_STORAGE_KEY, nextCache);
  } catch (error) {
    console.error("写入调试日志失败:", error);
  }
};

/**
 * 格式化调试参数
 * @param arg 待格式化参数
 */
const formatDebugArg = (arg: unknown) => {
  if (typeof arg === "string") return arg;
  try {
    return JSON.stringify(arg);
  } catch (error) {
    return String(arg);
  }
};

/**
 * 打印调试日志，仅在 debug=1 时输出
 * @param args 日志参数
 */
const debugLog = (...args: unknown[]) => {
  if (!isDebugMode.value) return;
  const message = args.map((item) => formatDebugArg(item)).join(" ");
  appendDebugLog({
    timestamp: Date.now(),
    message,
  });
  console.log("[auth-callback]", ...args);
};

/**
 * 处理授权回调
 * @description 解析URL参数，获取授权code并处理
 */
const handleAuthCallback = async () => {
  try {
    isProcessing.value = true;
    isSuccess.value = false;
    isError.value = false;
    
    debugLog("开始处理微信授权回调");
    
    // 获取URL参数
    const urlParams = new URLSearchParams(window.location.search);
    const code = urlParams.get('code');
    const state = urlParams.get('state');
    const error = urlParams.get('error');
    
    debugLog("授权回调参数:", { code, state, error });
    
    // 检查是否有错误
    if (error) {
      throw new Error(`授权被拒绝: ${error}`);
    }
    
    // 检查必要参数
    if (!code) {
      throw new Error('未获取到授权码');
    }
    
    if (state !== '123') {
      throw new Error('授权状态验证失败');
    }
    
    // 成功获取到code，记录日志
    debugLog("✅ 成功获取微信授权code:", code);
    debugLog("📝 授权状态验证通过，state:", state);
    
    // 模拟处理时间
    await new Promise(resolve => setTimeout(resolve, 1500));
    
    // 调用授权管理器的回调处理方法，传入code
    await handleCodeExchange(code);
    
    // 再次检查授权结果
    if (wechatAuth.checkAuthStatus()) {
      isSuccess.value = true;
      debugLog("🎉 授权成功，token已保存");
      
      // 延迟跳转
      setTimeout(() => {
        Taro.redirectTo({
          url: '/pages/home/home'
        });
      }, 1500);
    } else {
      throw new Error('授权验证失败，请重试');
    }
  } catch (error) {
    console.error('❌ 处理授权回调失败:', error);
    debugLog("❌ 处理授权回调失败详情:", error);
    isError.value = true;
    errorMessage.value = error instanceof Error ? error.message : '授权处理失败，请重试';
  } finally {
    isProcessing.value = false;
  }
};

/**
 * 处理code换取token
 * @description 使用获取到的code调用后端接口换取token
 */
const handleCodeExchange = async (code: string) => {
  try {
    debugLog("🔄 开始使用code换取token...");
    
    // 调用后端接口，用code换取token
    // 这里需要根据你的后端API进行调整
    const response = await exchangeCodeForToken(code);
    
    if (response.success) {
      debugLog("✅ Token获取成功:", response.token);
      
      // 保存token到本地存储
      Taro.setStorageSync('token', response.token);
      Taro.setStorageSync('tokenExpireTime', response.expireTime);
      
      // 获取用户信息
      await fetchUserInfo(response.token);
      
    } else {
      throw new Error(response.message || 'Token获取失败');
    }
  } catch (error) {
    console.error('❌ Code换取token失败:', error);
    debugLog("❌ Code换取token失败详情:", error);
    throw error;
  }
};

/**
 * 调用后端接口换取token
 * @description 实际项目中需要调用你的后端API
 */
const exchangeCodeForToken = async (code: string) => {
  try {
    // 调用后端接口，使用code换取token
    const response = await post('/my/updateOpenID', { 
      code: code 
    });
    
    debugLog("后端接口响应:", response);
    
    if (response.code === 0) {
      return {
        success: true,
        token: response.data.token || 'wechat_token_' + Date.now(),
        expireTime: response.data.expireTime || Date.now() + 7200 * 1000,
        message: response.message || '授权成功'
      };
    } else {
      throw new Error(response.message || '授权失败');
    }
  } catch (error) {
    console.error('调用后端接口失败:', error);
    debugLog("调用后端接口失败详情:", error);
    throw error;
  }
};

/**
 * 获取用户信息
 * @description 使用token获取用户信息
 */
const fetchUserInfo = async (token: string) => {
  try {
    debugLog("🔄 获取用户信息...");
    
    // 实际项目中，这里应该调用获取用户信息的API
    // 例如：const userInfo = await get('/api/user/info', { headers: { Authorization: `Bearer ${token}` } });
    
    // 模拟获取用户信息
    const userInfo = {
      id: 'user_' + Date.now(),
      nickname: '微信用户',
      avatar: 'http://www.dzgktf.com/templets/default/images/wtyt.jpg'
    };
    
    // 保存用户信息到store
    // userStore.setUserInfo(userInfo);
    
    debugLog("✅ 用户信息获取成功:", userInfo);
  } catch (error) {
    console.error('❌ 获取用户信息失败:', error);
    debugLog("❌ 获取用户信息失败详情:", error);
    // 这里可以选择不抛出错误，因为token已经获取成功
  }
};

/**
 * 重试授权
 * @description 重新开始微信授权流程
 */
const handleRetry = () => {
  isProcessing.value = true;
  isSuccess.value = false;
  isError.value = false;
  errorMessage.value = '';
  
  // 重新开始授权流程
  setTimeout(() => {
    wechatAuth.authorize();
  }, 500);
};

/**
 * 返回登录页
 * @description 跳转回登录页面
 */
const goBackToLogin = () => {
  Taro.redirectTo({
    url: '/pages/webs/login'
  });
};

// 页面加载时处理授权回调
/**
 * 初始化调试状态
 * @description 支持通过 URL 参数开启/关闭调试并缓存状态
 */
const initDebugMode = () => {
  const urlParams = new URLSearchParams(window.location.search);
  const debugParam = urlParams.get("debug");

  if (debugParam === "1") {
    isDebugMode.value = true;
    Taro.setStorageSync(DEBUG_ENABLE_STORAGE_KEY, true);
    console.log("[auth-callback] Debug 模式通过 URL 启用并已缓存");
  } else if (debugParam === "0") {
    isDebugMode.value = false;
    Taro.removeStorageSync(DEBUG_ENABLE_STORAGE_KEY);
    console.log("[auth-callback] Debug 模式通过 URL 关闭并已清理缓存");
  } else {
    const cachedDebug = Taro.getStorageSync(DEBUG_ENABLE_STORAGE_KEY);
    isDebugMode.value = !!cachedDebug;
    if (isDebugMode.value) {
      console.log("[auth-callback] Debug 模式依据缓存启用");
    }
  }

  debugLog("Debug 模式已启用");
};

onMounted(() => {
  initDebugMode();
  handleAuthCallback();
});
</script>

<style scoped>
.loading-spinner {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style> 